/*
 * @Autor: xgq
 * @Description: 
 * @Version: 1.0
 * @Date: 2020-05-12 10:04:53
 */
var fs = require('fs')
const path = require('path')
var express = require('express');
var topic_router = express.Router();
var db = require('../../models');
var comm = require('../../comm')

// 整合专题内容方法
let integrationTopicInner = async (topic) => {
  for (var obj of topic) {
    obj.category_id = ''
    obj.category = {}
    obj.tag_id = []
    obj.tags = []
    obj.images = []
    let topic_inner = await db.topic_relation.gettopicInner(obj.id)
    for (var inner of topic_inner) {
      if (parseInt(obj.id) === parseInt(inner.topic_id)) {
        if (inner.tp_type === 1) {
          obj.category_id = inner.associated_id
          let target = JSON.parse(await comm.redhget('category', inner.associated_id))
          obj.category = { id: inner.associated_id, name: target.name, code: target.code }
        } else if (inner.tp_type === 2) {
          obj.tag_id.push(inner.associated_id)
          obj.tags.push({ id: inner.associated_id, name: await comm.redget(inner.associated_id) })
        } else {
          obj.images.push(inner.associated_id)
        }
      }
    }
  }
  return topic
};


// 添加专题
topic_router.post('/addTopic', async (req, res) => {
  var form = req.body
  let oldthumbnail = form.thumbnail
  let thumbnail = oldthumbnail.replace('temp_files/', '')
  var newthumbnail = `topic/${thumbnail}`
  var sourceFile = path.join(process.cwd(), 'static/temp_files', thumbnail);
  var targetPath = path.join(process.cwd(), 'static/images', newthumbnail);
  let oldpage_thumbnail = form.page_thumbnail
  let page_thumbnail = oldpage_thumbnail.replace('temp_files/', '')
  var newpage_thumbnail = `topic/${page_thumbnail}`
  var page_sourceFile = path.join(process.cwd(), 'static/temp_files', page_thumbnail);
  var page_targetPath = path.join(process.cwd(), 'static/images', newpage_thumbnail);
  await comm.move_image(sourceFile, targetPath)
  await comm.move_image(page_sourceFile, page_targetPath)
  let create_time = parseInt(new Date().getTime() / 1000);
  var result = await db.topic.sequelize.transaction(t => {
    return db.topic.create({
      name: form.name,
      thumbnail: newthumbnail,
      page_thumbnail:newpage_thumbnail,
      title: form.title,
      status: form.status,
      sort: form.sort,
      link: form.link,
      tp_type: form.tp_type,
      create_time,
      position: form.position
    }, {
      transaction: t
    }).then((data) => {
      if (form.tp_type == 4) {
        return data
      }
      let topic_id = data.dataValues.id;
      if (form.tp_type === 1) {
       return db.topic_relation.create({
          topic_id,
          associated_id: form.category_id,
          tp_type: 1
        },{transaction:t})
      }

      if (form.tp_type === 2) {
        var promises = []
        for (var associated2_id of form.tag_id) {
          var newPromises=db.topic_relation.create({
            topic_id,
            associated_id: associated2_id,
            tp_type: 2
          },{transaction:t})
          promises.push(newPromises)
        }
        return Promise.all(promises).then(() => {
          return true
        })
      }

      if (form.tp_type === 3) {
        var promises = []
        var arr=form.image_id.split(',')
        for (var associated3_id of form.image_id) {
          if(arr){
            var newPromises=db.topic_relation.create({
              topic_id,
              associated_id: associated3_id,
              tp_type: 3
            },{transaction:t})
          }
        }
        return Promise.all(promises).then(() => {
          return true
        })
      }
    }).catch(err => {
      console.log(err)
    })
  })
    .then(result => {
      console.log('result', result)
      return result
    }).catch(err => {
      console.log('catch', err)
      return null
    })
  res.json(result)
})




// admin获取专题
topic_router.get('/getTopics', async (req, res) => {
  var [page = 1, pagesize = 30] = [req.query.pageNo, req.query.pageSize]
  let condition = {
    "pagesize": pagesize,
    "page": page
  }
  let topic = await db.topic.getTopics(condition)

  let r = await integrationTopicInner(topic.rows)
  let data = {
    code: 200,
    rows: r
  }
  res.json(data)
})

// 通过id或name搜索专题
topic_router.post('/getTopicByIdOrName', async (req, res) => {
  let result = await db.topic.getTopicByIdOrName(req.body.queryString)
  res.json(result)
})



// 修改状态
topic_router.get('/alterTopicStatus', async (req, res) => {
  let pars = req.query
  let result = await db.topic.alterTopicStatus(pars);
  res.json(result)
})


// 修改专题
topic_router.post('/editTopics', async (req, res) => {
  let form = req.body
  let id = req.body.id
  let thumbnail = req.body.thumbnail
  let page_thumbnail = req.body.page_thumbnail
  let topic = await db.topic.getTopicById(id)
  if (topic.thumbnail !== thumbnail) {
    comm.delete_imgage(path.join(process.cwd(), "static/images/", topic.thumbnail))
    var sourceFile = path.join(process.cwd(), 'static', thumbnail);
    thumbnail = thumbnail.replace('temp_files/', 'topic/')
    var targetPath = path.join(process.cwd(), 'static/images', thumbnail);
    await comm.move_image(sourceFile, targetPath)
  }
  if ( topic.page_thumbnail !== null && topic.page_thumbnail !== page_thumbnail) {
    comm.delete_imgage(path.join(process.cwd(), "static/images/", topic.page_thumbnail))
    var sourceFile = path.join(process.cwd(), 'static', page_thumbnail);
    page_thumbnail = page_thumbnail.replace('temp_files/', 'topic/')
    var targetPath = path.join(process.cwd(), 'static/images', page_thumbnail);
    await comm.move_image(sourceFile, targetPath)
  }
  let result = await db.topic.sequelize.transaction(t => {
    return db.topic.update({
      name: form.name,
      thumbnail: thumbnail,
      page_thumbnail:page_thumbnail,
      status: form.status,
      position: form.position,
      sort: form.sort,
      link: form.link,
      tp_type: form.tp_type,
    }, {
      where: {
        id: form.id
      },
      transaction: t
    }).then((data) => {
      return db.topic_relation.destroy({
        where: {
          topic_id: form.id
        },
        transaction: t
      }).then(re => {
        let topic_id = form.id;
        if (form.tp_type == 1) {
          return db.topic_relation.create({
            topic_id,
            associated_id: form.category_id,
            tp_type: 1
          }, { transaction: t })
        } else if (form.tp_type == 2) {
          var promises = []
          for (var associated_id of form.tag_id) {
            var newPromises = db.topic_relation.create({
              topic_id,
              associated_id: associated_id,
              tp_type: 2
            }, { transaction: t })
            promises.push(newPromises)
          }
          return Promise.all(promises).then(() => {
            return true
          })
        } else if (form.tp_type == 3) {
          var promises = []
          var arr=form.image_id.split(',')
          for (var associated_id of arr) {
            if(associated_id){
              var newPromises = db.topic_relation.create({
                topic_id,
                associated_id: associated_id,
                tp_type: 3
              }, { transaction: t })
            }
          }
          return Promise.all(promises).then(() => {
            return true
          })
        }
        return true
      }).catch(err => {
        console.log(err)
      })
    })
  })
    .then(result => {
      return result
    }).catch(err => {
      return null
    })
  res.json(result)
})


// // 获取一个专题下的图数量
// let getImgCountByTopic=async (topic_id)=>{
//   let count=await img_info.ImgInfoModel.fornt_getImgCountByTopic(topic_id)
//   return count;
// }

/**
 * @author: xgq
 * @description: 客户端首页推荐
 * @param {type} 
 * @return: 
 */
topic_router.post('/fornt_homeRecommendation', async (req, res) => {
  var [page = 1, pagesize = 12, order = 'ASC', orderBy = 'sort'] = [req.body.pageNo, req.body.pageSize, req.body.order, req.body.orderBy]
  let condition = {
    "pagesize": pagesize,
    "page": page,
    'order': order,
    'orderBy': orderBy
  }
  let topiclist = await db.topic.fornt_homeRecommendation(condition)
  // for(var item of topiclist){
  //   if(item.tp_type==1){
  //     let count=await getImgCountByTopic(item.id);
  //     item.imgCount=count
  //   }else{
  //     item.imgCount='按链接跳转'
  //   }
  // }
  res.json(topiclist)
})

// 客户端首页获取新品推荐
topic_router.post('/fornt_getNewTopics', async (req, res) => {
  var [page = 1, pagesize = 12] = [req.query.pageNo, req.query.pageSize]
  let condition = {
    "pagesize": pagesize,
    "page": page
  }
  let topic = await db.topic.fornt_getNewTopics(condition)
  let r = await integrationTopicInner(topic)
  res.json(r)
})

//删除专题
topic_router.post('/deleteTopic', async (req, res) => {
  let result = { 'code': 500 }
  let id = req.body.id
  let topic = await db.topic.getTopicById(id)
  comm.delete_imgage(topic.thumbnail)
  if (topic == null) {
    return res.json(result)
  }
  comm.delete_imgage(path.join(process.cwd(), "static/images/", topic.thumbnail))
  result = await db.topic.sequelize.transaction(t => {
    return db.topic_relation.destroy({
      where: {
        topic_id: id
      }
    }, {
      transaction: t
    }).then(user => {
      return db.topic.destroy({
        where: {
          id
        }
      }, {
        transaction: t
      })
    });
  }).then(result => {
    return result
  }).catch(err => {
    return null
  })
  res.json(result)
})
/**
 * @author: Shihh
 * @description: 获取所有图片类型组成的专题
 * @param {type} 
 * @return: 
 */
topic_router.post('/getImgTopic', async (req, res) => {
  let result = await db.topic.findAll({
    attributes:['name','id','sort','position'],
    where:{
      tp_type:req.body.tp_type
    },
    order:[['sort','ASC']],
    raw:true
  })
  res.json(result)
})

/**
 * @author: Shihh
 * @description: 添加多张图片到图片专题
 * @param {type} 
 * @return: 
 */
topic_router.post('/imagesInTopic',async(req,res)=>{
  let images=req.body.imageId
  let topic=req.body.topic
  images.forEach( item => {
     db.topic_relation.findCreateFind({
      where: { topic_id: topic.id, associated_id: item,tp_type:3},
      defaults: { topic_id: topic.id, associated_id: item,tp_type:3 },
    }).catch(err=>{
      console.log(err)
    })
  });
  res.json({
    code:200
  })
})

/**
 * @author: xgq
 * @description: 通过id或name获取专题
 * @param {type} 
 * @return: 
 */
topic_router.post('/findByIdorName', async (req, res) => {
  let result = await db.category.getCategoryByNameOrById(req.body.queryString)
  res.json(result)
})

//拖动排序
topic_router.post('/topicSort', async (req, res) => {
  //start拖动的目的地
  //end从哪一行开始拖动的
  //start《end从后往前拖动   start》end从前往后拖动
  let result = await db.topic.topicSort(req.body.params)
  res.json(result)
})


// 获取列表条数，用于添加排序
topic_router.get('/getTopicCount', async (req, res) => {
  let result = await db.topic.getTopicCount()
  res.json(result)
})



module.exports = topic_router
